package com.smartboot.plus.plugins.api;


import com.smartboot.plus.plugins.AbstractFeature;
import com.smartboot.plus.plugins.PluginConfig;
import org.smartboot.socket.enhance.EnhanceAsynchronousChannelProvider;
import tech.smartboot.feat.cloud.FeatCloud;
import tech.smartboot.feat.core.common.logging.Logger;
import tech.smartboot.feat.core.common.logging.LoggerFactory;
import tech.smartboot.feat.core.server.HttpServer;
import tech.smartboot.mqtt.common.util.MqttUtil;
import tech.smartboot.mqtt.plugin.spec.BrokerContext;

import java.nio.channels.AsynchronousChannelGroup;
import java.util.concurrent.ThreadFactory;

public class FeatApiPlugin extends AbstractFeature {
    private static final Logger LOGGER = LoggerFactory.getLogger(FeatApiPlugin.class);

    private PluginConfig.HttpConfig featApiConfig;

    private HttpServer httpServer;
    private AsynchronousChannelGroup asynchronousChannelGroup;
    private PluginConfig pluginConfig;

    public FeatApiPlugin(BrokerContext context, PluginConfig pluginConfig ) {
        super(context);
        this.pluginConfig = pluginConfig;
        featApiConfig = pluginConfig.getHttpConfig();
        MqttUtil.updateConfig(featApiConfig, "openApi");

    }

    @Override
    public String name() {
        return "openApi";
    }


    @Override
    public void start() throws Exception {

        asynchronousChannelGroup = new EnhanceAsynchronousChannelProvider(false)
                .openAsynchronousChannelGroup(Runtime.getRuntime().availableProcessors(), new ThreadFactory() {
                    int i;

                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "featApi-" + (++i));
                    }
                });

        //启动feat
        httpServer = FeatCloud.cloudServer(ops -> {

            ops.addExternalBean("brokerContext", context);
            ops.addExternalBean("pluginConfig", pluginConfig);
            ops.group(asynchronousChannelGroup);
            ops.readBufferSize(featApiConfig.getReadBufferSize());
            //注入其他bean
//            cloudOptions.getExternalBeans().forEach((key, value) -> {
//                ops.addExternalBean(key, value);
//            });
        });
        httpServer.listen(context.Options().getHost(), featApiConfig.getPort());

    }

    @Override
    public void destroy() {
        if (httpServer != null) {
            httpServer.shutdown();
            httpServer = null;
        }
        if (asynchronousChannelGroup != null) {
            asynchronousChannelGroup.shutdown();
            asynchronousChannelGroup = null;
        }
    }
}
